document.addEventListener('DOMContentLoaded', function () {
    console.log('=== JavaScript脚本开始加载 ===');
    console.log('DOM内容已加载完成');
    
    const socket = io();
    console.log('Socket.IO已初始化:', socket);

    // --- DOM Elements ---
    const navLinks = document.querySelectorAll('.nav-link');
    const contentSections = document.querySelectorAll('.content-section');
    
    const uploadBtns = document.querySelectorAll('.upload-btn');
    const fileInputs = document.querySelectorAll('.json-upload-input');
    const startBtns = document.querySelectorAll('.start-btn');
    const statusTexts = document.querySelectorAll('.status-text');

    // Training section elements
    const trainingStartBtn = document.querySelector('.start-btn[data-purpose="training"]');
    const trainingStatusText = document.querySelector('#training-section .status-text');

    // Validation section elements
    const validationStartBtn = document.querySelector('.start-btn[data-purpose="validation"]');
    const validationStatusText = document.querySelector('#validation-section .status-text');
    
    // 安全地获取模型文本元素
    const trainingCurrentModelElement = document.getElementById('training-current-model-text');
    const trainingCurrentModelText = trainingCurrentModelElement ? trainingCurrentModelElement.querySelector('span') : null;
    
    const validationCurrentModelElement = document.getElementById('validation-current-model-text');
    const validationCurrentModelText = validationCurrentModelElement ? validationCurrentModelElement.querySelector('span') : null;
    
    const downloadModelBtn = document.getElementById('download-model-btn');
    const uploadModelBtn = document.getElementById('upload-model-btn');
    const modelUploadInput = document.getElementById('model-upload-input');

    // User testing elements
    const selectImageBtn = document.getElementById('select-image-btn');
    const imageUploadInput = document.getElementById('image-upload-input');
    const imagePreview = document.getElementById('image-preview');
    const predictBtn = document.getElementById('predict-btn');
    const predictionResultText = document.getElementById('prediction-result-text');

    // JSON Generator elements
    const executeSqlBtn = document.getElementById('execute-sql-btn');
    const downloadJsonBtn = document.getElementById('download-json-btn');
    const sqlInput = document.getElementById('sql-input');
    const jsonResultContainer = document.getElementById('json-result-container');
    const jsonPreview = document.getElementById('json-preview');
    const jsonInfo = document.getElementById('json-info');
    const jsonGeneratorStatusText = document.querySelector('#json-generator-section .status-text');

    let uploadedTrainingFileName = null;
    let uploadedValidationFileName = null;
    let currentModelName = null;
    let generatedJsonFilename = null;

    // --- Chart Instances ---
    let charts = {};

    function createChart(canvasId, label, borderColor, backgroundColor) {
        const ctx = document.getElementById(canvasId).getContext('2d');
        if (charts[canvasId]) {
            charts[canvasId].destroy();
        }
        charts[canvasId] = new Chart(ctx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [{
                    label: label,
                    data: [],
                    borderColor: borderColor,
                    backgroundColor: backgroundColor,
                    borderWidth: 2,
                    fill: true,
                    tension: 0.3
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    x: { title: { display: true, text: 'Step' } },
                    y: { title: { display: true, text: 'Value' }, beginAtZero: true }
                },
                animation: { duration: 200 }
            }
        });
    }

    function resetChart(canvasId) {
        if (charts[canvasId]) {
            charts[canvasId].data.labels = [];
            charts[canvasId].data.datasets[0].data = [];
            charts[canvasId].update();
        }
    }
    
    function addDataToChart(canvasId, label, data) {
        const chart = charts[canvasId];
        if (chart) {
            chart.data.labels.push(label);
            chart.data.datasets[0].data.push(data);
            chart.update();
        }
    }

    // Initialize all charts
    function initializeCharts() {
        createChart('trainingLossChart', 'Loss', 'rgba(231, 76, 60, 1)', 'rgba(231, 76, 60, 0.1)');
        createChart('trainingAccChart', 'Accuracy (%)', 'rgba(52, 152, 219, 1)', 'rgba(52, 152, 219, 0.1)');
        createChart('validationLossChart', 'Loss', 'rgba(243, 156, 18, 1)', 'rgba(243, 156, 18, 0.1)');
        createChart('validationAccChart', 'Accuracy (%)', 'rgba(46, 204, 113, 1)', 'rgba(46, 204, 113, 0.1)');
    }

    // --- Navigation ---
    navLinks.forEach(link => {
        link.addEventListener('click', (e) => {
            e.preventDefault();
            const targetId = link.getAttribute('data-target');

            navLinks.forEach(navLink => navLink.classList.remove('active'));
            link.classList.add('active');

            contentSections.forEach(section => {
                section.classList.remove('active');
                if (section.id === targetId) {
                    section.classList.add('active');
                    
                    console.log(`切换到页面: ${targetId}`);
                    
                    // 当切换到验证页面时，刷新模型列表
                    if (targetId === 'validation-section') {
                        console.log('检测到切换到验证页面，即将刷新模型列表...');
                        setTimeout(() => {
                            console.log('开始执行刷新模型列表...');
                            if (typeof refreshModelList === 'function') {
                                console.log('调用 refreshModelList 函数');
                                refreshModelList();
                            } else {
                                console.error('refreshModelList 函数未定义');
                            }
                        }, 100);
                    }
                }
            });
        });
    });

    // --- File Upload Logic ---
    uploadBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            const purpose = btn.dataset.purpose;
            const input = document.querySelector(`.json-upload-input[data-purpose="${purpose}"]`);
            if (input) {
                input.click();
            } else {
                console.error(`未找到对应的文件输入元素: .json-upload-input[data-purpose="${purpose}"]`);
            }
        });
    });

    fileInputs.forEach(input => {
        input.addEventListener('change', function() {
            if (this.files.length > 0) {
                const file = this.files[0];
                const formData = new FormData();
                const purpose = this.dataset.purpose;
                formData.append('file', file);
                formData.append('purpose', purpose);

                const statusText = document.querySelector(`#${purpose}-section .status-text`);
                const startBtn = document.querySelector(`.start-btn[data-purpose="${purpose}"]`);

                statusText.textContent = `正在上传 ${file.name}...`;

                fetch('/upload', {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        statusText.textContent = `文件 ${file.name} 上传成功。准备好开始。`;
                        if (purpose === 'training') {
                            uploadedTrainingFileName = data.filename;
                        } else if (purpose === 'validation') {
                            uploadedValidationFileName = data.filename;
                        }
                        startBtn.disabled = false;
                    } else {
                        statusText.textContent = `上传失败: ${data.error || '未知错误'}`;
                        startBtn.disabled = true;
                    }
                })
                .catch(error => {
                    console.error('Upload error:', error);
                    statusText.textContent = `上传出错: ${error.message || error}`;
                    startBtn.disabled = true;
                });
            }
        });
    });

    // --- Training Logic ---
    if (trainingStartBtn) {
        trainingStartBtn.addEventListener('click', function () {
            if (uploadedTrainingFileName) {
                this.disabled = true;
                if (trainingStatusText) {
                    trainingStatusText.textContent = '正在请求开始训练，这一步比较缓慢，请耐心等待。';
                }
                resetChart('trainingLossChart');
                resetChart('trainingAccChart');
                socket.emit('start_training', { 'filename': uploadedTrainingFileName });
            } else {
                if (trainingStatusText) {
                    trainingStatusText.textContent = '请先上传一个训练JSON文件。';
                }
            }
        });
    }

    // --- Validation Logic ---
    if (validationStartBtn) {
        validationStartBtn.addEventListener('click', function () {
            if (uploadedValidationFileName) {
                // 获取当前选中的模型名
                const modelSelectElement = document.getElementById('model-select');
                const selectedModel = modelSelectElement ? modelSelectElement.value : '';
                if (!selectedModel) {
                    if (validationStatusText) {
                        validationStatusText.textContent = '请先选择要验证的模型文件。';
                    }
                    return;
                }
                this.disabled = true;
                if (validationStatusText) {
                    validationStatusText.textContent = '正在请求开始验证...';
                }
                resetChart('validationLossChart');
                resetChart('validationAccChart');
                // 传递模型名和验证文件名给后端
                socket.emit('start_validation', { 'filename': uploadedValidationFileName, 'model_name': selectedModel });
            } else {
                if (validationStatusText) {
                    validationStatusText.textContent = '请先上传一个验证JSON文件。';
                }
            }
        });
    }

    // --- Model Management Logic ---
    if (downloadModelBtn) {
        downloadModelBtn.addEventListener('click', function() {
            if (!currentModelName) {
                alert('当前没有可下载的模型。');
                return;
            }
            window.location.href = '/download_model';
        });
    }

    if (uploadModelBtn && modelUploadInput) {
        uploadModelBtn.addEventListener('click', () => modelUploadInput.click());
    }

    modelUploadInput.addEventListener('change', function() {
        if (this.files.length > 0) {
            const file = this.files[0];
            const formData = new FormData();
            formData.append('file', file);

            validationStatusText.textContent = `正在上传模型 ${file.name}...`;

            fetch('/upload_model', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    validationStatusText.textContent = `模型上传成功。当前模型已设置为: ${data.model_name}`;
                    updateCurrentModel(data.model_name);
                } else {
                    validationStatusText.textContent = `模型上传失败: ${data.error}`;
                }
            })
            .catch(error => {
                validationStatusText.textContent = `上传请求失败: ${error}`;
            });
        }
    });

    function updateCurrentModel(modelName) {
        currentModelName = modelName;
        if (trainingCurrentModelText) {
            trainingCurrentModelText.textContent = modelName || '无';
        }
        if (validationCurrentModelText) {
            validationCurrentModelText.textContent = modelName || '无';
        }
        if (downloadModelBtn) {
            downloadModelBtn.disabled = !modelName;
        }
    }

    // --- 模型下拉刷新与切换 ---
    const modelSelect = document.getElementById('model-select');
    const setModelBtn = document.getElementById('set-model-btn');
    const refreshModelsBtn = document.getElementById('refresh-models-btn');

    // 手动刷新按钮事件
    if (refreshModelsBtn) {
        refreshModelsBtn.addEventListener('click', function() {
            console.log('用户点击了手动刷新按钮');
            if (validationStatusText) {
                validationStatusText.textContent = '正在刷新模型列表...';
            }
            window.refreshModelList();
        });
    }

    // 立即定义全局函数，确保它们可用
    window.refreshModelList = function() {
        console.log('=== 开始刷新模型列表 ===');
        
        // 重新获取下拉框元素，确保DOM已加载
        const modelSelectElement = document.getElementById('model-select');
        console.log('模型选择元素:', modelSelectElement);
        
        if (!modelSelectElement) {
            console.error('模型选择下拉框未找到，DOM可能尚未加载完成');
            return;
        }

        console.log('发送请求到 /api/list_models...');
        fetch('/api/list_models')
            .then(res => {
                console.log('收到响应状态:', res.status);
                console.log('响应对象:', res);
                if (!res.ok) {
                    throw new Error(`HTTP ${res.status}: ${res.statusText}`);
                }
                return res.json();
            })
            .then(data => {
                console.log('=== API返回的完整数据 ===');
                console.log(JSON.stringify(data, null, 2));
                
                // 清空下拉
                modelSelectElement.innerHTML = '<option value="">请选择要切换的模型 (.pth)</option>';
                if (data.models && data.models.length > 0) {
                    console.log(`找到 ${data.models.length} 个模型文件:`);
                    data.models.forEach((name, index) => {
                        console.log(`  ${index + 1}. ${name}`);
                        const opt = document.createElement('option');
                        opt.value = name;
                        opt.textContent = name;
                        modelSelectElement.appendChild(opt);
                    });
                    console.log(`成功加载 ${data.models.length} 个模型到下拉列表`);
                    console.log('当前下拉框选项:', modelSelectElement.innerHTML);
                    
                    // 更新状态文本
                    const validationStatusElement = document.querySelector('#validation-section .status-text');
                    if (validationStatusElement) {
                        validationStatusElement.textContent = `已找到 ${data.models.length} 个模型文件`;
                    }
                } else {
                    console.log('未找到任何模型文件');
                    const validationStatusElement = document.querySelector('#validation-section .status-text');
                    if (validationStatusElement) {
                        validationStatusElement.textContent = '未找到任何模型文件';
                    }
                }
            })
            .catch(error => {
                console.error('刷新模型列表失败:', error);
                // 如果存在状态文本元素，显示错误
                const validationStatusElement = document.querySelector('#validation-section .status-text');
                if (validationStatusElement) {
                    validationStatusElement.textContent = `刷新模型列表失败: ${error.message}`;
                }
            });
    };
    
    // 添加全局测试函数
    window.testRefresh = function() {
        console.log('手动测试刷新功能被调用');
        window.refreshModelList();
    };

    // 页面加载时立即刷新一次 - 增加多重保障
    console.log('准备设置定时器调用refreshModelList');
    setTimeout(() => {
        console.log('500ms定时器触发，调用refreshModelList');
        if (typeof window.refreshModelList === 'function') {
            window.refreshModelList();
        } else {
            console.error('refreshModelList函数未定义');
        }
    }, 500);
    
    setTimeout(() => {
        console.log('1000ms定时器触发，调用refreshModelList');
        if (typeof window.refreshModelList === 'function') {
            window.refreshModelList();
        }
    }, 1000);
    
    setTimeout(() => {
        console.log('2000ms定时器触发，调用refreshModelList');
        if (typeof window.refreshModelList === 'function') {
            window.refreshModelList();
        }
    }, 2000);
    
    // 也在窗口完全加载后再次刷新
    window.addEventListener('load', function() {
        console.log('窗口完全加载，再次刷新模型列表');
        setTimeout(() => {
            if (typeof window.refreshModelList === 'function') {
                window.refreshModelList();
            }
        }, 100);
    });
    
    // 切换到验证tab时也刷新（这个现在由导航处理）

    // 切换当前模型
    if (setModelBtn) {
        setModelBtn.addEventListener('click', function() {
            // 重新获取下拉框元素
            const modelSelectElement = document.getElementById('model-select');
            const selected = modelSelectElement ? modelSelectElement.value : '';
            
            if (!selected) {
                if (validationStatusText) {
                    validationStatusText.textContent = '请选择要切换的模型文件！';
                }
                return;
            }
            
            fetch('/api/set_model', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ model_name: selected })
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    validationStatusText.textContent = `已切换为模型: ${data.model_name}`;
                    updateCurrentModel(data.model_name);
                } else {
                    validationStatusText.textContent = `切换失败: ${data.error}`;
                }
            })
            .catch(error => {
                validationStatusText.textContent = `切换请求失败: ${error}`;
            });
        });
    }


    // --- User Testing Logic ---
    if (selectImageBtn && imageUploadInput) {
        selectImageBtn.addEventListener('click', () => imageUploadInput.click());
    }

    if (imageUploadInput && imagePreview) {
        imageUploadInput.addEventListener('change', function() {
            if (this.files && this.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    imagePreview.src = e.target.result;
                    imagePreview.style.display = 'block';
                    if (predictBtn) {
                        predictBtn.disabled = false;
                    }
                    if (predictionResultText) {
                        predictionResultText.textContent = '-';
                    }
                }
                reader.readAsDataURL(this.files[0]);
            }
        });
    }

    if (predictBtn) {
        predictBtn.addEventListener('click', function() {
            if (!imageUploadInput || !imageUploadInput.files[0]) {
                if (predictionResultText) {
                    predictionResultText.textContent = '请先选择一张图片。';
                }
                return;
            }
            
            const file = imageUploadInput.files[0];
            this.disabled = true;
            if (predictionResultText) {
                predictionResultText.textContent = '正在识别中...';
            }

            const formData = new FormData();
            formData.append('file', file);

        fetch('/predict', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.prediction) {
                predictionResultText.textContent = data.prediction;
            } else {
                predictionResultText.textContent = `错误: ${data.error}`;
            }
            })
            .catch(error => {
                if (predictionResultText) {
                    predictionResultText.textContent = `请求失败: ${error}`;
                }
            })
            .finally(() => {
                this.disabled = false;
            });
        });
    }


    // --- Socket.IO Event Handlers ---
    socket.on('connect', () => {
        console.log('已通过Socket.IO连接到服务器');
    });

    socket.on('status_update', function(data) {
        // Try to update status on the active tab first
        const activeStatus = document.querySelector('.content-section.active .status-text');
        if (activeStatus) {
            activeStatus.textContent = data.msg;
        } else { // Fallback to all status texts if none is active
            statusTexts.forEach(text => text.textContent = data.msg);
        }
    });

    socket.on('update_stats', function(data) {
        const step = `${data.epoch}-${data.step}`;
        addDataToChart('trainingLossChart', step, data.loss);
        addDataToChart('trainingAccChart', step, data.accuracy);
    });

    socket.on('training_complete', function(data) {
        trainingStatusText.textContent = data.msg;
        trainingStartBtn.disabled = false; // Re-enable button
        updateCurrentModel(data.model_name);
    });

    socket.on('update_validation_stats', function(data) {
        addDataToChart('validationLossChart', data.step, data.loss);
        addDataToChart('validationAccChart', data.step, data.accuracy);
    });

    socket.on('validation_complete', function(data) {
        if (validationStatusText) {
            validationStatusText.textContent = data.msg;
        }
        if (validationStartBtn) {
            validationStartBtn.disabled = false; // Re-enable button
        }
    });

    socket.on('current_model_info', function(data) {
        updateCurrentModel(data.model_name);
    });

    // --- JSON Generator Logic ---
    if (executeSqlBtn) {
        executeSqlBtn.addEventListener('click', function() {
            const sqlQuery = sqlInput ? sqlInput.value.trim() : '';
            
            if (!sqlQuery) {
            jsonGeneratorStatusText.textContent = '请输入SQL查询语句';
            return;
        }
        
        this.disabled = true;
        jsonGeneratorStatusText.textContent = '正在执行SQL查询...';
        jsonResultContainer.style.display = 'none';
        downloadJsonBtn.disabled = true;
        
        fetch('/execute_sql', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ sql: sqlQuery })
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                generatedJsonFilename = data.filename;
                jsonGeneratorStatusText.textContent = `SQL执行成功！生成了 ${data.total_records} 条记录`;
                
                // 显示JSON预览
                jsonPreview.textContent = JSON.stringify(data.preview, null, 2);
                jsonInfo.textContent = `文件名: ${data.filename} | 总记录数: ${data.total_records} | 显示前 ${data.preview.length} 条记录`;
                jsonResultContainer.style.display = 'block';
                downloadJsonBtn.disabled = false;
            } else {
                jsonGeneratorStatusText.textContent = `执行失败: ${data.error || '未知错误'}`;
            }
            })
            .catch(error => {
                console.error('SQL execution error:', error);
                if (jsonGeneratorStatusText) {
                    jsonGeneratorStatusText.textContent = `执行出错: ${error.message || error}`;
                }
            })
            .finally(() => {
                this.disabled = false;
            });
        });
    }

    if (downloadJsonBtn) {
        downloadJsonBtn.addEventListener('click', function() {
            if (!generatedJsonFilename) {
                alert('没有可下载的JSON文件');
                return;
            }
            window.location.href = '/download_generated_json';
        });
    }

    // --- Initial Setup ---
    initializeCharts();
    // Request initial model info on page load
    socket.emit('request_initial_model');
});

